package cn.wanho.config.handler;

import cn.wanho.dto.ExamUser;
import cn.wanho.redis.RedisManger;
import cn.wanho.rvo.ResultEnum;
import cn.wanho.rvo.ResultVO;
import cn.wanho.service.user.UserService;
import cn.wanho.util.JWTUtil01;
import cn.wanho.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * @Author: heyang
 * @Description: 登录成功处理逻辑
 * @Date Create in 2022/8/6 15:52
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    UserService userService;

    @Resource
    RedisManger redisManger;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //更新用户表上次登录时间、更新人、更新时间等字段
        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println();
        ExamUser examUser = userService.selectByName(userDetails.getUsername());
        //实现jwt,最后一个设置为null，代表24小时过期
        String jwtToken = JWTUtil01.createJWT(examUser.getId().toString(), examUser.getUserName(), "loginUser", null);

        //此处还可以进行一些处理，比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限，
        //进而前台动态的控制菜单的显示等，具体根据自己的业务需求进行扩展

        //返回json数据
        redisManger.saveJWT(Math.toIntExact(examUser.getId()), jwtToken);
        httpServletResponse.setContentType("text/json;charset=utf-8");
        HashMap<String, String> token = new HashMap<>();
        token.put("token",jwtToken);
        httpServletResponse.getWriter().write(JsonUtil.toJson(
                ResultVO.success(ResultEnum.SUCCESS.getResCode(), ResultEnum.SUCCESS.getResMsg(), token)));

    }
}
